import pygame

pygame.init()
pygame.joystick.init()

# 检测已连接的手柄数量
joystick_count = pygame.joystick.get_count()
print(f"检测到 {joystick_count} 个手柄")

if joystick_count > 0:
    # 获取第一个手柄对象
    joystick = pygame.joystick.Joystick(0)
    joystick.init()
    print(f"手柄名称: {joystick.get_name()}")
else:
    print("未检测到手柄！")

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        #通过event判断手柄是否有输入
        if event.type == pygame.JOYBUTTONDOWN:  # 检测按钮按下事件
            print(f"按钮 {event.button} 被按下")
        elif event.type == pygame.JOYBUTTONUP:  # 检测按钮释放事件
            print(f"按钮 {event.button} 被释放")
        elif event.type == pygame.JOYAXISMOTION:  # 检测摇杆移动事件
            print(f"摇杆 {event.axis} 移动到 {event.value}")
        elif event.type == pygame.JOYHATMOTION:  # 检测方向键事件
            print(f"方向键 {event.value}")
pygame.quit()